package com.jd.event.spring.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.jd.event.EventContainer;
import com.jd.event.EventListener;
import com.jd.event.service.GroupScheduledService;

public class SpringGroupScheduledService extends GroupScheduledService
		implements InitializingBean, ApplicationContextAware {
	ApplicationContext applicationContext;
	protected List<ListenerDescription> listnerDescs;

	public SpringGroupScheduledService() {

	}

	public SpringGroupScheduledService(String group, EventContainer container) {
		super(group, container);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (this.listnerDescs != null) {
			List<EventListener> eventListeners = new ArrayList<EventListener>();
			for (ListenerDescription desc : listnerDescs) {
				if (StringUtils.isBlank(desc.ref)
						&& StringUtils.isBlank(desc.className)) {
					continue;
				}
				EventListener listener = null;
				if (StringUtils.isNotBlank(desc.ref)) {
					listener = (EventListener) applicationContext
							.getBean(desc.ref);
				} else {
					listener = (EventListener) Class.forName(desc.className)
							.newInstance();
				}

				eventListeners.add(listener);
			}

			if (!eventListeners.isEmpty()) {
				this.container.addListeners(group, eventListeners);
			}
		}

	}

	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		applicationContext = context;
	}

	public void setListnerDescs(List<ListenerDescription> listnerDescs) {
		this.listnerDescs = listnerDescs;
	}

}
